package book;

import constant.Constant;
import utils.AnalyzingBook;
import utils.ScannerSingleton;

import java.io.IOException;
import java.time.Instant;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.Scanner;
import java.time.LocalDate;

public class Library {

    public Book[] books;//存储书籍的数组
    public int bookCount;//记录当前图书馆到底有效的书籍有多少本
    private AnalyzingBook analyzingBook = new AnalyzingBook();
    private Scanner scanner;

    public Library() {
        //读
        loadAllBook();
        scanner = ScannerSingleton.getInstance();
    }
    //写为一个独立的方法，后期可以实时更新到底多少本书
    private void loadAllBook(){
        try {
            books = new Book[Constant.CAPACITY];
            Book[] allBook = analyzingBook.loadObject(Constant.ALL_BOOK_FILE_NAME);
            if(allBook == null){
                bookCount = 0;
            }else {
                int allBookLen = allBook.length;
                if(allBookLen > books.length){
                    books = new Book[allBookLen];
                }

                for (int i = 0; i < allBookLen; i++) {
                    books[i] = allBook[i];
                }
                //有效的书籍
                bookCount = allBookLen;
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    //存储书籍到文件当中
    private void storeBook() {
        try {
            analyzingBook.storeObject(books,Constant.ALL_BOOK_FILE_NAME);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    //公用的方法
    public void searchBook(){
        System.out.println("查找图书");
        scanner.nextLine();
        System.out.println("请输⼊你要查找的图书的名称：");
        String title = scanner.nextLine();
        Book book = search(title);
        if(book == null) {
            System.out.println("没有你要找的这本书，你查找的书名为："+title);
        }else {
            System.out.println("找到了你要查找的书，书的详细信息如下：");
            System.out.println(book);
        }

    }
    //根据title查找对应书籍
    private Book search(String title) {
        loadAllBook();
        for (int i = 0; i < bookCount; i++) {
            Book book = books[i];

            if (book.getTitle().equals(title)) {
                return book;
            }
        }
        return null;
    }
    public void displayBooks(){
        System.out.println("显示图书");
        loadAllBook();
        for (int i = 0; i < bookCount; i++) {
            System.out.println(books[i]);
        }
    }
    public void exit(){
        System.out.println("已经成功退出系统！！！");
        System.exit(0);

    }

    //添加图书
    public void addBook(Book book) {
        if(bookCount >= books.length){
            System.out.println("图书馆已满，⽆法上架更多图书！");
            return;
        }
        books[bookCount] = book;
        Book bookLast = books[bookCount-1];
        bookCount++;
        book.setBookId(bookLast.getBookId() + 1);
        //此时存储数据的时候 会把书籍对象全部存储，虽然部分属性没有输⼊赋值
        storeBook();
        System.out.println("图书 "+book.getTitle()+"上架成功！");

    }

   // 更新图书
    public void updateBook(Book book) {
        //先找到该书是哪个下标
        int bookId = book.getBookId();
        int index = searchByIdReturnIndex(bookId);
        if(index == -1){
            System.out.println("不存在你要更新的书籍，此时的bookId为" + bookId);
            return;
        }
        books[index] = book;
        //⼀定要进⾏存储
        storeBook();
        System.out.print("书籍已被更新，文件重新写入，更新之后的书籍为：");
        System.out.println(books[index]);
    }
    //根据bookId 返回 书籍索引位置
    private int searchByIdReturnIndex(int bookId) {
        loadAllBook();
        for (int i = 0; i < bookCount; i++) {
            Book book = books[i];
            if(book.getBookId()==bookId) {
                return i;
            }
        }
        return -1;
    }
    //根据bookId 查找对应书籍
    public Book searchById(int bookId) {
        loadAllBook();
        for (int i = 0; i < bookCount; i++) {
            Book book = books[i];
            if(book.getBookId()==bookId) {
                return book;
            }
        }
        return null;
    }

    public void removeBook(int bookId) {
        int index = searchByIdReturnIndex(bookId);
        if(index == -1){
            System.out.println("没有你要删除的书籍");
            return;
        }
        //开始删除 从当前位置的后边往前移动
        for (int i = index; i < bookCount-1; i++) {
            books[i] = books[i+1];
        }
        bookCount--;
        books[bookCount] = null;
        storeBook();
    }

    public void borrowCount() {
        loadAllBook();
        for (int i = 0; i < bookCount; i++) {
            Book book = books[i];
            System.out.println("书名:"+book.getTitle()+
                    " 借阅次数："+book.getBorrowCount());
        }
    }

    public void generateBook(int k) {
        //1. 加载已有的全部的书籍
        loadAllBook();
        //2.把所有书籍放在 临时数据 进⾏排序
        Book[] tmp = new Book[bookCount];
        for (int i = 0; i < bookCount; i++) {
            tmp[i] = books[i];
        }
        //2.1 开始排序
        Arrays.sort(tmp);
        //3. 把前k本书拷⻉到新数组 可以不定义临时数组，直接输出前K个就⾏
        Book[] generateBooks = new Book[k];
        for (int i = 0; i < k; i++) {
            generateBooks[i] = tmp[i];
        }
        //4.打印新数组
        System.out.println("最受欢迎书籍如下：");
        for (int i = 0; i < generateBooks.length; i++) {
            Book book = generateBooks[i];
            System.out.println("书籍ID: "+i+" 书名："+ book.getTitle()+" 作者："+
                    book.getTitle()+" 借阅次数："+book.getBorrowCount());
        }
    }

    public void checkInventoryStatus() {
        loadAllBook();
        for (int i = 0; i < bookCount; i++) {
            Book book = books[i];
            String status = book.isBorrowed() ? "已借出" : "在馆";
            System.out.println("书名："+book.getTitle()+" ⽬前状态："+status);
        }
    }

    public void checkAndRemoveOldBooks(Scanner scanner) {
        // 获取当前时间戳
        long currentTimestamp = System.currentTimeMillis();
        // 将当前时间戳转换为 LocalDate
        LocalDate currentDate = Instant.ofEpochMilli(currentTimestamp)
                .atZone(ZoneId.systemDefault())
                .toLocalDate();
        boolean flg = false;
        for (int i = 0; i < bookCount; i++) {
            Book book = books[i];
            //获取当前书籍的上架时间
            LocalDate specifiedDate = book.getShelfDate();
            // 计算两个⽇期之间的差值（以年为单位）
            long yearsBetween = ChronoUnit.YEARS.between(specifiedDate, currentDate);
            if (yearsBetween >= 1) {
                System.out.print("图书 " + book.getTitle() + " 已经上架超过⼀年，是否移除？ (y/n)：");
                scanner.nextLine();
                String response = scanner.nextLine();
                if (response.equalsIgnoreCase("y")) {
                    //确认删除调⽤remove⽅法进⾏删除
                    removeBook(book.getBookId());
                    //i--; // 因为后⾯的书已经向前移动，所以要重新检查当前索引位置
                }
                flg = true;
            }
        }
        if (!flg) {
            System.out.println("没有上架超过⼀年的图书！");
        }
        storeBook();
    }


    public void borrowBook(int bookId) {
        loadAllBook();

        Book book = searchById(bookId);
        book.setBorrowed(true);
        book.incrementBorrowCount();

        storeBook();
    }

    public void returnBook(int bookId) {
        loadAllBook();
        for (int i = 0; i < bookCount; i++) {
            Book book = books[i];
            if(book.getBookId()==bookId) {
                book.setBorrowed(false);
                book.decrementBorrowCount();
            }
        }
        storeBook();
    }


}
